<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title>人脸登录</title>
    <style>
        * {
            margin: 0px;
            padding: 0px;
            box-sizing: border-box;
        }

        #circle {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            height: 60vh;
            width: 80vw;
            border-radius: 50%;
            border: 4px dashed red;
        }
        #msg{
            color:yellow;
            position: absolute;
            top:2vh;
            width:100%;
            text-align: center;
            font-size: 3em;
            animation: shine 1s infinite linear;
        }
        #video2{
            position:absolute;
            width:100%;
            height:100%;
            display:none;
            top:50%;
            transform:translateY(-50%);
            margin:0;
            padding: 0;
            background-color: transparent;
            object-fit: cover;
        }
        @keyframes shine{
            0%{
                opacity: 1;
            }
            50%{
                opacity: .5;
            }
            100%{
                opacity: 1;
            }
        }
    </style>
</head>

<body style="overflow: hidden;height:100%;width:100%;background-color:#000;">
<canvas id="canvasCemara" width="500" height="500" style="position: absolute;z-index: -1;opacity: 0;"></canvas>
<video autoplay="" id="video2" ></video>
<div id="circle">
</div>
<div id="msg">
    请将人脸移入框内!
</div>
<script type="text/javascript" charset="utf-8">
    !function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).uni=n()}(this,(function(){"use strict";try{var e={};Object.defineProperty(e,"passive",{get:function(){!0}}),window.addEventListener("test-passive",null,e)}catch(e){}var n=Object.prototype.hasOwnProperty;function t(e,t){return n.call(e,t)}var i=[],a=function(e,n){var t={options:{timestamp:+new Date},name:e,arg:n};if(window.__dcloud_weex_postMessage||window.__dcloud_weex_){if("postMessage"===e){var a={data:[n]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(a):window.__dcloud_weex_.postMessage(JSON.stringify(a))}var o={type:"WEB_INVOKE_APPSERVICE",args:{data:t,webviewIds:i}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(o):window.__dcloud_weex_.postMessageToService(JSON.stringify(o))}if(!window.plus)return window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:t,pageId:""},"*");if(0===i.length){var r=plus.webview.currentWebview();if(!r)throw new Error("plus.webview.currentWebview() is undefined");var d=r.parent(),s="";s=d?d.id:r.id,i.push(s)}if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:t,webviewIds:i}},"__uniapp__service");else{var w=JSON.stringify(t);plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat("WEB_INVOKE_APPSERVICE",'",').concat(w,",").concat(JSON.stringify(i),");"))}},o={navigateTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("navigateTo",{url:encodeURI(n)})},navigateBack:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.delta;a("navigateBack",{delta:parseInt(n)||1})},switchTab:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("switchTab",{url:encodeURI(n)})},reLaunch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("reLaunch",{url:encodeURI(n)})},redirectTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("redirectTo",{url:encodeURI(n)})},getEnv:function(e){window.plus?e({plus:!0}):e({h5:!0})},postMessage:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a("postMessage",e.data||{})}},r=/uni-app/i.test(navigator.userAgent),d=/complete|loaded|interactive/;var s=window.my&&navigator.userAgent.indexOf("AlipayClient")>-1;var w=window.swan&&window.swan.webView&&/swan/i.test(navigator.userAgent);var u=window.qq&&window.qq.miniProgram&&/QQ/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var c=window.tt&&window.tt.miniProgram&&/toutiaomicroapp/i.test(navigator.userAgent);var g=window.wx&&window.wx.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var v=window.qa&&/quickapp/i.test(navigator.userAgent);for(var p,l=function(){window.UniAppJSBridge=!0,document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady",{bubbles:!0,cancelable:!0}))},_=[function(e){if(r)return window.__dcloud_weex_postMessage||window.__dcloud_weex_?document.addEventListener("DOMContentLoaded",e):window.plus&&d.test(document.readyState)?setTimeout(e,0):document.addEventListener("plusready",e),o},function(e){if(g)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.wx.miniProgram},function(e){if(u)return window.QQJSBridge&&window.QQJSBridge.invoke?setTimeout(e,0):document.addEventListener("QQJSBridgeReady",e),window.qq.miniProgram},function(e){if(s){document.addEventListener("DOMContentLoaded",e);var n=window.my;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(w)return document.addEventListener("DOMContentLoaded",e),window.swan.webView},function(e){if(c)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(v){window.QaJSBridge&&window.QaJSBridge.invoke?setTimeout(e,0):document.addEventListener("QaJSBridgeReady",e);var n=window.qa;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){return document.addEventListener("DOMContentLoaded",e),o}],f=0;f<_.length&&!(p=_[f](l));f++);p||(p={});var m="undefined"!=typeof uni?uni:{};if(!m.navigateTo)for(var E in p)t(p,E)&&(m[E]=p[E]);return m.webView=p,m}));
</script>
<script>

    function ajax(options) {
        options = options || {};
        options.type = (options.type || "GET").toUpperCase();
        options.dataType = options.dataType || "json";
        var params = formatParams(options.data);

        //创建 - 非IE6 - 第一步
        if (window.XMLHttpRequest) {
            var xhr = new XMLHttpRequest();
        } else { //IE6及其以下版本浏览器
            var xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }

        //接收 - 第三步
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.fail && options.fail(status);
                }
            }
        }

        //连接 和 发送 - 第二步
        if (options.type == "GET") {
            xhr.open("GET", options.url + "?" + params, true);
            xhr.send(null);
        } else if (options.type == "POST") {
            xhr.open("POST", options.url, true);
            //设置表单提交时的内容类型
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(params);
        }
    }
    //格式化参数
    function formatParams(data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
        }
        arr.push(("v=" + Math.random()).replace(".",""));
        return arr.join("&");
    }
    document.addEventListener('UniAppJSBridgeReady', function() {
        var video = document.getElementById('video2');
        var msg = document.getElementById('msg')
        var constraints = { audio: false, video: true, facingMode: "user" };
        function successCallback(stream) {
            video.srcObject = stream;
            video.play();
            setTimeout(()=>{
                video.style.display = 'block'
            },1000)


        }
        function errorCallback(error) {
            console.log("navigator.getUserMedia error: ", error);
        }
        navigator.getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.msGetUserMedia ||
            navigator.mediaDevices.getUserMedia||
            navigator.getUserMedia//||null ;//获取媒体对象（这里指摄像头）
        // if(navigator.getUserMedia){
        navigator.getUserMedia(constraints, successCallback, errorCallback)
        // }
        // .then(successCallback)
        // .catch(errorCallback);

        var i = 5;
        function takePhoto() {

            if(i==0){
                uni.postMessage({
                    data: {
                        action: -1
                    }
                });
                return;
            }
            var video = document.getElementById('video2');
            canvas = document.getElementById('canvasCemara');
            ctx = canvas.getContext('2d');
            var _w = 400, _h = 300;
            if (video.videoWidth > 0) {
                _h = video.videoHeight / (video.videoWidth / _w);
            }
            canvas.setAttribute('width', _w);
            canvas.setAttribute('height', _h);
            ctx.fillRect(0, 0, _w, _h);
            ctx.drawImage(video, 0, 0, _w, _h);
            var quality = 1;
            let src = canvas.toDataURL("image/jpeg", quality)
            console.log('========================')
            let url = 'https://garbage-collection-platform.jyxws.cn/api/user/faceLoginWithImg'
            var data = {
                img: src,
                site:getQuery('site')
            };
            ajax({
                url: url,
                type: 'POST',
                data: data,
                success: function (res) {
                    console.log(res)
                    let data = JSON.parse(res)
                    console.log(data.errcode)
                    if(data.errcode==0){
                        msg.innerHTML = '<div style="color:rgb(16,201,33);">识别成功！</div>'
                        //向uniapp传值
                        uni.postMessage({
                            data: {
                                action: res
                            }
                        });
                    }
                    else{
                        msg.innerHTML = '<div style="color:red;">未识别到正确的人脸</div><div style="color:red;">请将人脸移入框内</div>'
                    }

                },
                fail: function (err) {
                    console.log(err)
                }
            });
            if (i > 0) {
                i--;
                setTimeout(takePhoto, 3000);
            }

        }
        takePhoto()
        //取url中的参数值
        function getQuery(name) {
            // 正则：[找寻'&' + 'url参数名字' = '值' + '&']（'&'可以不存在）
            let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            let r = window.location.search.substr(1).match(reg);
            console.log(r);
            if(r != null) {
                // 对参数值进行解码
                return decodeURIComponent(r[2]);
            }
            return null;
        }
    });
</script>

</body>

</html>